<script>
    var IMG_URL = "<?php img_url()?>";
    $(document).ready(function () {
        $(".header-cart-popup").click(function () {
            $("#myCart").modal("show");
            $(".cart-item-table-row").remove();
            $.get("<?php nav_url("shop/addToCart/")?>", function (response) {
                if (!response.error) {
                    $("#cart-loader").hide();
                    $("#cart-message").hide();
                    $("#cart-user-register").hide();
                    $("#footer-action-btn").show();
                    if (response.data.length > 0) {
                        var actualTotalAmount = 0;
                        var discountTotalAmount = 0;
                        var estimateTotalAmount = 0;
                        for (var i = 0; i < response.data.length; i++) {
                            var item = response.data[i];
                            var row = $("#cart-item-template").clone().show();
                            $(row).attr("id", "cart_" + item.cartId);
                            $(row).addClass("cart-item-table-row");
                            $(row).find(".cart-product-img").attr("src", IMG_URL + item.img);
                            $(row).find(".cart-product-name").text(item.name);
                            $(row).find(".cart-product-discount").text(item.discount + " %");
                            $(row).find(".cart-product-price").html("<i style='font-size:13px' class='fa fa-rupee'/> " + item.price);
                            $(row).find(".cart-product-qty").text(item.quantity);
                            $(row).find(".cart-product-subtotal").html("<i style='font-size:13px' class='fa fa-rupee'/> " + item.subtotal);
                            $(row).find(".remove").attr("id", item.cartId);
                            $("#cart-table").append(row);
                            actualTotalAmount += item.subtotal;
                            discountTotalAmount += item.subtotal - item.discountTotal;
                            estimateTotalAmount += item.discountTotal;
                        }
                        $("#header-cart-popup").html(response.data.length + " item - <i class='fa fa-rupee'/>" + parseFloat(estimateTotalAmount).toFixed(2));
                        $("#cart-total").text(parseFloat(actualTotalAmount).toFixed(2));
                        $("#cart-discount").text(parseFloat(discountTotalAmount).toFixed(2));
                        $("#cart-estimated-total").text(parseFloat(estimateTotalAmount).toFixed(2));
                        $("#cart-table-container").show();
                        $("#place-order").removeAttr("disabled");
                    } else {
                        $("#place-order").attr("disabled", "disabled");
                        $("#cart-message").show();
                        $("#cart-message").html("<h3>No Product was found in cart !</h3>");
                    }
                }
            });
        });
    });

    $(document).ready(function () {
        $("body").on("click", "a.remove-cart-item", function () {
            var cartid = $(this).attr("id");
            $.get("<?php nav_url("shop/removeFromCart/")?>" + cartid, function (response) {
                $("#cart-message").hide();
                if (!response.error) {
                    $("#cart_" + cartid).slideUp("fast");
                    $("#cart_" + cartid).remove();

                    var actualTotalAmount = 0;
                    var discountTotalAmount = 0;
                    var estimateTotalAmount = 0;
                    for (var i = 0; i < response.data.length; i++) {
                        var item = response.data[i];
                        actualTotalAmount += item.subtotal;
                        discountTotalAmount += item.subtotal - item.discountTotal;
                        estimateTotalAmount += item.discountTotal;
                    }
                    $("#header-cart-popup").html(response.data.length + " item - <i class='fa fa-rupee'/>" + parseFloat(estimateTotalAmount).toFixed(2));
                    $("#cart-total").text(parseFloat(actualTotalAmount).toFixed(2));
                    $("#cart-discount").text(parseFloat(discountTotalAmount).toFixed(2));
                    $("#cart-estimated-total").text(parseFloat(estimateTotalAmount).toFixed(2));

                    if (response.data.length == 0) {
                        $("#cart-table-container").hide();
                        $("#cart-message").show();
                        $("#cart-message").html("<h3>No Product was found in cart !</h3>");
                    }else{
                        $("#place-order").removeAttr("disabled");
                    }
                } else {
                    errorAlert(response.errorMessage);
                }
            });
        });

        $("#place-order").click(function () {
            $("#cart-table-container").hide();
            $("#cart-loader").show();
            $.get("<?php nav_url("shop/isUserLoggedIn")?>",function(response){
                if(response.loggedIn){
                    $.get("<?php nav_url("shop/placeOrder")?>", function (response) {
                        $("#cart-message").show();
                        $("#cart-message").html("");
                        var responseHtml = "";
                        if (!response.error) {
                            var responseHtml = "<h3> Order placed Successfully</h3>";
                            responseHtml += "<h5> Order No: " +  response.data.orderId + "</h5>";
                            responseHtml += "<h6> Order Details are mail to : " + response.data.email + "</h6>";
                            responseHtml += "<p>" + response.data.message + "</p>";
                        } else {
                            responseHtml = response.data.errorMessage;
                        }
                        $("#cart-message").html(responseHtml);
                    }).always(function(){
                            $("#cart-loader").hide();
                    });
                }else{
                    $("#cart-user-register").show();
                    $("#footer-action-btn").hide();
                    $("#cart-loader").hide();
                }
            });

        });

        $.validate({
            form: '#registerform-placeorder',
            validateOnBlur: false,
            onError: function () {
                return false;
            },
            onSuccess: function ($form) {
                var btn = Ladda.create(document.querySelector("#order-register-account-btn"));
                btn.start();
                $.post("<?php nav_url("shop/registerandplaceorder") ?>", $form.serialize(),function (response) {
                    $("#cart-user-register").hide();
                    $("#cart-message").show();
                    $("#cart-message").html("");
                    if (!response.error) {
                        var responseHtml = "<h3> Order placed Successfully </h3>";
                        responseHtml += "<h5> Order No: " +  response.data.orderId + "</h5>";
                        responseHtml += "<h6> Order Details are mail to : " + response.data.email + "</h6>";
                        responseHtml += "<p>" + response.data.message + "</p>";
                    } else {
                        responseHtml = response.data.errorMessage;
                    }
                    $("#cart-message").html(responseHtml);
                }).always(function () {
                        btn.stop();
                }).fail(function(response){
                    alert(JSON.stringify(response));
                });
                return false;
            }
        });

        $(".subscribe").click(function(){
            $.post("<?php nav_url("shop/subscribe") ?>","subscribe_email="+$("#subscribe-email").val(),function(){
                $("#subscribe-email").val("");
            });
        });
    });
</script>

<script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-61014495-1', 'auto');
    ga('send', 'pageview');

</script>